/*
 * Copyright 2020 Liu Jie <jieliu2000@live.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.beyondsoft.sabg.edu.controller.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.beyondsoft.sabg.edu.model.db.core.BinaryFile;
import com.beyondsoft.sabg.edu.model.db.core.Image;
import com.beyondsoft.sabg.edu.model.exception.GenericBusinessException;
import com.beyondsoft.sabg.edu.model.vo.core.SimpleResponseVO;
import com.beyondsoft.sabg.edu.service.core.BinaryFileService;
import com.beyondsoft.sabg.edu.service.core.ImageService;
import com.beyondsoft.sabg.edu.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * 图片
 * @Author Mo cr
 * @Date 2023/11/14
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class ImageController {

    @Autowired
    BinaryFileService binaryService;
    @Autowired
    ImageService imageService;
    @Autowired
    HttpServletRequest request;



    @RequestMapping(value = "/image/upload", method = RequestMethod.POST)
    public SimpleResponseVO upload(@RequestParam(value = "file", required = false) MultipartFile file
            , HttpServletRequest request) {
        Image image;
        try {
            image = binaryService.saveImage(file);
            return ResponseUtil.success().withData(image.getUrlId());
        }catch (Exception ex){
            log.error(ex.getMessage());
            throw new GenericBusinessException("文件上传失败:"+ex.getMessage());
        }
    }

    @RequestMapping(value = "/image/get/{fileID}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> showImage(
            @PathVariable("fileID") final String urlId)
            throws IOException {
        if(StrUtil.isEmpty(urlId)){
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        Long id = null;
        try {
            String u = new String(Base64Utils.decodeFromString(urlId));
            id = Long.parseLong(u);
        } catch (Exception e) {
            throw new GenericBusinessException("process error:" + e);
        }

        if (id == null) {
            throw new GenericBusinessException("image id is null");
        }

        Image image = imageService.findById(id).get();

        String fileName = image.getName();

        byte[] bytes = image.getBinaryContents();

        HttpHeaders responseHeaders = new HttpHeaders();
        String contentType = image.getContentType();
        if ("image/jpg".equals(image.getContentType())) {
            contentType = "image/jpeg";
        }
        responseHeaders.setContentType(MediaType.parseMediaType(contentType));
        responseHeaders.setContentLength(bytes.length);
        responseHeaders.setContentDispositionFormData("inline", id + "");

        return new ResponseEntity<byte[]>(bytes,
                responseHeaders, HttpStatus.OK);
    }
}
